import { Window_Base } from "@/windows/Window_Base.js";
import { config } from "@/managers/ConfigManager.js";
import { Input } from "@/core/Input.js";
import { TouchInput } from "@/core/TouchInput.js";

export class Window_ScrollText extends Window_Base {
    constructor() {
        super(0, 0);
        this.windowFrame.visible = false;
        this._text = '';
        this._allTextHeight = 0;

        this.hide();
    }

    windowWidth(){
        return config.width;
    }
    windowHeight(){
        return config.height;
    }

    update() {
        super.update();
        if ($gameMessage.scrollMode()) {
            if (this._text) {
                this.updateMessage();
            }
            if (!this._text && $gameMessage.hasText()) {
                this.startMessage();
            }
        }
    }

    startMessage() {
        this._text = $gameMessage.allText();
        this.refresh();
        this.show();
    }

    refresh() {
        let textState = { index: 0 };
        textState.text = this.convertEscapeCharacters(this._text);
        this.resetFontSettings();
        this._allTextHeight = this.calcTextHeight(textState, true);
        this.createContents();
        this.contents.y = -this.height;
        this.drawTextEx(this._text, this.textPadding(), 1);
    }

    contentsHeight() {
        return Math.max(this._allTextHeight, 1);
    }

    updateMessage() {
        this.y += this.scrollSpeed();
        if (this.contents.y >= this.contents.height) {
            this.terminateMessage();
        }
    }

    scrollSpeed() {
        let speed = $gameMessage.scrollSpeed() / 2;
        if (this.isFastForward()) {
            speed *= this.fastForwardRate();
        }
        return speed;
    }

    isFastForward() {
        if ($gameMessage.scrollNoFast()) {
            return false;
        } else {
            return (Input.isPressed('ok') || Input.isPressed('shift') ||
                    TouchInput.isPressed());
        }
    }

    fastForwardRate() {
        return 3;
    }

    terminateMessage() {
        this._text = null;
        $gameMessage.clear();
        this.hide();
    }
}